package com.mstar.qs.common.json;

import java.util.Collection;
import java.util.Map;
import java.util.Set;

public class JsonObject {

	private Map<String, String> keymap;
	private Set<String> excluded;
	private String text;
	private Object o;

	public JsonObject(Object o) {
		this(o, null, null);
	}

	public JsonObject(Object o, Map<String, String> keymap, Set<String> excluded) {
		if (o == null)
			throw new NullPointerException();
		this.o = o;
		this.keymap = keymap;
		this.excluded = excluded;
	}

	public String toJson() {
		if (text == null)
			convert();
		return text;
	}

	public String toString() {
		return toJson();
	}

	private void convert() {
		synchronized (o) {
			if (text == null) {
				if (o instanceof Collection) {
					text = new JsonArray((Collection) o, keymap, excluded)
							.toString();
					return;
				}
				if (o.getClass().isArray()) {
					try {
						text = new JsonArray(o, keymap, excluded).toString();
					} catch (JsonException e) {
						e.printStackTrace();
					}
					return;
				}
				if (o instanceof Map) {
					text = new JsonBean((Map) o, keymap, excluded).toString();
					return;
				}
				text = new JsonBean(o, keymap, excluded).toString();
			}
		}
	}

}
